<?php
class Purchase_Order extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'purchase_order',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	/**
	 * 创建采购单
	 * @param $order 采购单信息
	 */
	static function createOrder($order)
	{
		$generate_result = Number_Rules::generate('purchase_order', 'CG');
		if ($generate_result['ack'] == SUCCESS)
		{
			$budget_amount = 0;
			foreach ($order['item'] as $oi)
			{
				$budget_amount += $oi['budget_quantity'] * $oi['budget_price'];
			}
			$purchase_order = new Purchase_Order();
			$purchase_order->number = $generate_result['number'];
			$purchase_order->type = Q::ini('custom_flag/purchase_order_type/order/value');
			$purchase_order->payment_type = $order['payment_type'];
			$purchase_order->warehouse_id = $order['warehouse_id'];
			$purchase_order->purchase_user_id = $order['purchase_user_id'];
			$purchase_order->purchase_time = $order['purchase_time'];
			$purchase_order->notes = $order['notes'];
			$purchase_order->budget_amount = $budget_amount;
			$purchase_order->status = Q::ini('custom_flag/purchase_order_status/new/value');
			$purchase_order->make_user_id = CURRENT_USER_ID;
			$purchase_order->make_time = CURRENT_DATETIME;
			$purchase_order->save();
			$purchase_order_id = mysql_insert_id();
			Purchase_Order_Item::updateBudget($order['item'], $purchase_order_id);
			return array('ack' => SUCCESS, 'message' => '', 'purchase_order_id' => $purchase_order_id);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'cannot create number');
		}
	}
	
	/**
	 * 修改采购单预算信息
	 * @param $order 采购单信息
	 */
	static function editBudget($order)
	{
		$judge_result = Purchase_Order::judgeEditBudget($order['id']);
		if ($judge_result['ack'] == SUCCESS)
		{
			$purchase_order = Purchase_Order::find('id=?', $order['id'])->getOne();
			$budget_amount = 0;
			foreach ($order['item'] as $oi)
			{
				$budget_amount += $oi['budget_quantity'] * $oi['budget_price'];
			}
			$purchase_order->purchase_user_id = $order['purchase_user_id'];
			$purchase_order->purchase_time = $order['purchase_time'];
			$purchase_order->notes = $order['notes'];
			$purchase_order->payment_type = $order['payment_type'];
			$purchase_order->budget_amount = $budget_amount;
			$purchase_order->save();
			Purchase_Order_Item::updateBudget($order['item'], $order['id']);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 修改采购单实际采购信息
	 * @param $order 采购单信息
	 */
	static function editActual($order)
	{
		$judge_result = Purchase_Order::judgeEditActual($order['id']);
		if ($judge_result['ack'] == SUCCESS)
		{
			$update_item_result = Purchase_Order_Item::updateActual($order['item'], $order['id'], true);
			if ($update_item_result['ack'] == SUCCESS)
			{
				$item = Purchase_Order_Item::find('purchase_order_id=?', $order['id'])->asArray()->getAll();
				$actual_amount = 0;
				foreach ($item as $i)
				{
					$actual_amount += $i['actual_quantity'] * $i['actual_price'];
				}
				$purchase_order = Purchase_Order::find('id=?', $order['id'])->getOne();
				$purchase_order->actual_amount = $actual_amount;
				if ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/purchasing/value'))
				{
					$purchase_order->status = Q::ini('custom_flag/purchase_order_status/purchased/value');
				}
				if ( ! $purchase_order['complete_time'])
				{
					$purchase_order->complete_user_id = CURRENT_USER_ID;
					$purchase_order->complete_time = CURRENT_DATETIME;
				}
				if (isset($order['purchase_hold_flag']))
				{
					$purchase_order->purchase_hold_flag = $order['purchase_hold_flag'];
				}
				$purchase_order->save();
				Purchase_Order::updateOrder($order['id']);
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => $update_item_result['ack'], 'message' => $update_item_result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 删除采购单
	 * @param $purchase_order_id
	 */
	static function del($purchase_order_id)
	{
		$judge_result = Purchase_Order::judgeDel($purchase_order_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			Purchase_Order_Item::del($purchase_order_id);
			Purchase_Order::meta()->deleteWhere('id=?', $purchase_order_id);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 创建采购退货单
	 * @param $drawback 退货单信息
	 */
	static function createDrawback($drawback)
	{
		$judge_result = Purchase_Order::judgeCreateDrawback($drawback);
		if ($judge_result['ack'] == SUCCESS)
		{
			$generate_result = Number_Rules::generate('purchase_order', 'CT');
			if ($generate_result['ack'] == SUCCESS)
			{
				$actual_amount = 0;
				foreach ($drawback['item'] as $di)
				{
					$actual_amount += $di['actual_quantity'] * $di['actual_price'];
				}
				$purchase_order = new Purchase_Order();
				$purchase_order->number = $generate_result['number'];
				$purchase_order->type = Q::ini('custom_flag/purchase_order_type/drawback/value');
				$purchase_order->payment_type = $drawback['payment_type'];
				$purchase_order->warehouse_id = $drawback['warehouse_id'];
				$purchase_order->purchase_user_id = $drawback['purchase_user_id'];
				$purchase_order->purchase_time = $drawback['purchase_time'];
				$purchase_order->notes = $drawback['notes'];
				$purchase_order->actual_amount = $actual_amount;
				$purchase_order->status = Q::ini('custom_flag/purchase_order_status/new/value');
				$purchase_order->make_user_id = CURRENT_USER_ID;
				$purchase_order->make_time = CURRENT_DATETIME;
				$purchase_order->save();
				$drawback_id = mysql_insert_id();
				Purchase_Order_Item::updateDrawback($drawback['item'], $drawback_id);
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $generate_result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 编辑采购退货单
	 * @param $drawback 退货单信息
	 */
	static function editDrawback($drawback)
	{
		$judge_result = Purchase_Order::judgeEditDrawback($drawback);
		if ($judge_result['ack'] == SUCCESS)
		{
			$actual_amount = 0;
			foreach ($drawback['item'] as $di)
			{
				$actual_amount += $di['actual_quantity'] * $di['actual_price'];
			}
			$drawback_order = Purchase_Order::find('id=?', $drawback['id'])->getOne();
			$drawback_order->payment_type = $drawback['payment_type'];
			$drawback_order->purchase_user_id = $drawback['purchase_user_id'];
			$drawback_order->purchase_time = $drawback['purchase_time'];
			$drawback_order->notes = $drawback['notes'];
			$drawback_order->actual_amount = $actual_amount;
			$drawback_order->save();
			Purchase_Order_Item::updateDrawback($drawback['item'], $drawback['id']);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 删除采购退货单
	 * @param $drawback_id 采购退货单id
	 */
	static function delDrawback($drawback_id)
	{
		$judge_result = Purchase_Order::judgeDelDrawback($drawback_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			Purchase_Order_Item::delDrawback($drawback_id);
			Purchase_Order::meta()->deleteWhere('id=?', $drawback_id);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 采购前审核
	 * @param $purchase_order_id 采购单id
	 */
	static function auditPurchase($purchase_order_id)
	{
		$judge_result = Purchase_Order::judgeAuditPurchase($purchase_order_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->getOne();
			$purchase_order->status = Q::ini('custom_flag/purchase_order_status/purchasing/value');
			$purchase_order->purchase_audit_user_id = CURRENT_USER_ID;
			$purchase_order->purchase_audit_time = CURRENT_DATETIME;
			$purchase_order->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 仓库已到仓审核
	 * @param $purchase_order_id 采购单id
	 */
	static function auditWarehoused($purchase_order_id)
	{
		$judge_result = Purchase_Order::judgeAuditWarehoused($purchase_order_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->getOne();
			$purchase_order_item = Purchase_Order_Item::find('purchase_order_id=?', $purchase_order_id)->asArray()->getAll();
			foreach ($purchase_order_item as $item)
			{
				Product_Warehouse::purchaseActualQuantityIncrease(0, $item['product_basic_id'], $purchase_order['warehouse_id'], $item['actual_quantity']);
			}
			$purchase_order->status = Q::ini('custom_flag/purchase_order_status/arrived/value');
			$purchase_order->arrive_time = CURRENT_DATETIME;
			$purchase_order->arrive_user_id = CURRENT_USER_ID;
			$purchase_order->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 仓库批量确认发送到海外仓
	 * @param $purchae_order_item_ids
	 */
	static function auditSend($purchase_order_ids)
	{
		$message = array();
		foreach ($purchase_order_ids as $id)
		{
			$judge = Purchase_Order::judgeAuditSend($id);
			if ($judge['ack'] == SUCCESS)
			{
				$purchase_order = Purchase_Order::find('id=?', $id)->getOne();
				$purchase_order->status = Q::ini('custom_flag/purchase_order_status/send/value');
				$purchase_order->send_time = CURRENT_DATETIME;
				$purchase_order->send_user_id = CURRENT_USER_ID;
				$purchase_order->save();
			}
			else
			{
				$message[] = $judge['message'];
			}
		}
		if ($message)
		{
			return array('ack' => PARTIAL_FAILURE, 'message' => implode("\n", $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 仓库返回已到仓的采购单为已采购状态
	 * @param 订单ids $purchase_order_ids
	 */
	static function returnPurchased($purchase_order_ids)
	{
		$message = array();
		foreach ($purchase_order_ids as $purchase_order_id)
		{
			$judge = Purchase_Order::judgeReturnPurchased($purchase_order_id);
			if ($judge['ack'] == SUCCESS)
			{
				$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->getOne();
				$purchase_order->status = Q::ini('custom_flag/purchase_order_status/purchased/value');
				$purchase_order->arrive_time = '';
				$purchase_order->arrive_user_id = '';
				$purchase_order->save();
				$item = Purchase_Order_Item::find('purchase_order_id=?', $purchase_order_id)->asArray()->getAll();
				foreach ($item as $i)
				{
					Product_Warehouse::purchaseActualQuantityDecrease(0, $i['product_basic_id'], $purchase_order['warehouse_id'], $i['actual_quantity']);
				}
			}
			else
			{
				$message[] = $judge['message'];
			}
		}
		if ($message)
		{
			return array('ack' => PARTIAL_FAILURE, 'message' => implode("\n", $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	static function judgeReturnPurchased($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/arrived/value'))
			{
				$item = Purchase_Order_Item::find('purchase_order_id=?', $purchase_order['id'])->asArray()->getAll();
				$audit_flag = false;
				foreach ($item as $i)
				{
					if ($i['audit_flag'] == Q::ini('custom_flag/purchase_order_item_audit_flag/audited/value'))
					{
						$audit_flag = true;
					}
				}
				if ($audit_flag)
				{
					return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：采购单存在已审核入库产品，请联系系统技术人员！');
				}
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：采购单状态不是已到仓');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '不存在该采购单id=' . $purchase_order_id);
		}
	}
	
	/**
	 * 仓库审核入库（单个）
	 * @param $purchase_order_item_id 采购单item的id
	 */
	static function auditStorageSingle($purchase_order_item_id)
	{
		$judge_result = Purchase_Order::judgeAuditStorageSingle($purchase_order_item_id);
		if ($judge_result['ack'] == SUCCESS)
		{
			$default_currency = Currency::getDefaultCurrency();
			$item = Purchase_Order_Item::find('id=? and actual_quantity>0', $purchase_order_item_id)->getOne();
			$purchase_order = Purchase_Order::find('id=?', $item['purchase_order_id'])->getOne();
			$warehouse_id = $purchase_order['warehouse_id'];
			if ($item['id'])
			{
				$item->audit_flag = Q::ini('custom_flag/purchase_order_item_audit_flag/audited/value');
				$item->audit_time = CURRENT_DATETIME;
				$item->audit_user_id = CURRENT_USER_ID;
				$item->save();
				$log = new Inventory_Log();
				$log->product_basic_id = $item['product_basic_id'];
				$log->warehouse_id = $warehouse_id;
				$log->type = Q::ini('custom_flag/inventory_log_type/purchase/value');
				$log->relate_table_id = $item['id'];
				$log->init_quantity = 0;
				$log->in_quantity = $item['actual_quantity'];
				$log->out_quantity = 0;
				$log->cost_price = $item['actual_price'];
				$log->sales_price = 0;
				$log->cost_amount = $item['actual_quantity'] * $item['actual_price'];
				$log->sales_amount = 0;
				$log->currency_rate = $default_currency['rate'];
				$log->currency_id = $default_currency['id'];
				$log->remaining_quantity = $item['actual_quantity'];
				$log->user_id = CURRENT_USER_ID;
				$log->time = CURRENT_DATETIME;
				$log->save();
				QDB::getConn()->execute('update product_basic set preferred_provider_id='.$item['actual_provider_id'].' where id=' . $item['product_basic_id']);
				Product_Warehouse::actualQuantityIncrease(0, $item['product_basic_id'], $warehouse_id, $item['actual_quantity']);
				Product_Warehouse::availableQuantityIncrease(0, $item['product_basic_id'], $warehouse_id, $item['actual_quantity']);
				Product_Warehouse::purchaseBudgetQuantityDecrease(0, $item['product_basic_id'], $warehouse_id, $item['budget_quantity']);
				Product_Warehouse::purchaseActualQuantityDecrease(0, $item['product_basic_id'], $warehouse_id, $item['actual_quantity']);
				Product_Warehouse::purchaseQuantityDecrease(0, $item['product_basic_id'], $warehouse_id, $item['actual_quantity']);
				Product_Basic::updatePurchasePrice($item['product_basic_id'], $item['actual_price']);
				$item_audit_flag = true;
				$purchase_order_item = Purchase_Order_Item::find('purchase_order_id=? and actual_quantity>0', $item['purchase_order_id'])->asArray()->getAll();
				foreach ($purchase_order_item as $i)
				{
					if ($i['audit_flag'] == Q::ini('custom_flag/purchase_order_item_audit_flag/unaudited/value'))
					{
						$item_audit_flag = false;
					}
				}
				if ($item_audit_flag)
				{
					$purchase_order->status = Q::ini('custom_flag/purchase_order_status/storaged/value');
					$purchase_order->storage_audit_user_id = CURRENT_USER_ID;
					$purchase_order->storage_audit_time = $item['audit_time'];
					$purchase_order->save();
					$empty_actual_quantity_item = Purchase_Order_Item::find('purchase_order_id=? and actual_quantity=0 and audit_flag=' . Q::ini('custom_flag/purchase_order_item_audit_flag/unaudited/value'), $purchase_order_item_id)->asArray()->getAll();
					if ($empty_actual_quantity_item)
					{
						foreach ($empty_actual_quantity_item as $eaqi)
						{
							QDB::getConn()->execute('update purchase_order_item set audit_flag=' . Q::ini('custom_flag/purchase_order_item_audit_flag/audited/value') . ', audit_time=\'' . CURRENT_DATETIME . '\', audit_user_id=' . CURRENT_USER_ID . ' where id=' . $eaqi['id']);
							Product_Warehouse::purchaseBudgetQuantityDecrease(0, $eaqi['product_basic_id'], $warehouse_id, $eaqi['budget_quantity']);
						}
					}
				}
				else
				{
					$purchase_order->status = Q::ini('custom_flag/purchase_order_status/partial_storaged/value');
					$purchase_order->save();
				}
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'the item of actual quantity is zero');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 仓库审核入库
	 * @param $purchase_order_ids 采购单id
	 */
	static function auditStorage($purchase_order_ids)
	{
		$default_currency = Currency::getDefaultCurrency();
		$message = array();
		foreach ($purchase_order_ids as $id)
		{
			$judge_result = Purchase_Order::judgeAuditStorage($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				$purchase_order = Purchase_Order::find('id=?', $id)->getOne();
				$warehouse_id = $purchase_order['warehouse_id'];
				$purchase_order->status = Q::ini('custom_flag/purchase_order_status/storaged/value');
				$purchase_order->storage_audit_user_id = CURRENT_USER_ID;
				$purchase_order->storage_audit_time = CURRENT_DATETIME;
				$purchase_order->save();
				//inventory_log && product_warehouse
				$item = Purchase_Order_Item::find('purchase_order_id=? and actual_quantity>0 and audit_flag=' . Q::ini('custom_flag/purchase_order_item_audit_flag/unaudited/value'), $id)->asArray()->getAll();
				foreach ($item as $i)
				{
					$log = new Inventory_Log();
					$log->product_basic_id = $i['product_basic_id'];
					$log->warehouse_id = $warehouse_id;
					$log->type = Q::ini('custom_flag/inventory_log_type/purchase/value');
					$log->relate_table_id = $i['id'];
					$log->init_quantity = 0;
					$log->in_quantity = $i['actual_quantity'];
					$log->out_quantity = 0;
					$log->cost_price = $i['actual_price'];
					$log->sales_price = 0;
					$log->cost_amount = $i['actual_quantity'] * $i['actual_price'];
					$log->sales_amount = 0;
					$log->currency_rate = $default_currency['rate'];
					$log->currency_id = $default_currency['id'];
					$log->remaining_quantity = $i['actual_quantity'];
					$log->user_id = CURRENT_USER_ID;
					$log->time = CURRENT_DATETIME;
					$log->save();
					QDB::getConn()->execute('update product_basic set preferred_provider_id='.$i['actual_provider_id'].' where id=' . $i['product_basic_id']);
					QDB::getConn()->execute('update purchase_order_item set audit_flag=' . Q::ini('custom_flag/purchase_order_item_audit_flag/audited/value') . ', audit_time=\'' . CURRENT_DATETIME . '\', audit_user_id=' . CURRENT_USER_ID . ' where id=' . $i['id']);
					Product_Warehouse::actualQuantityIncrease(0, $i['product_basic_id'], $warehouse_id, $i['actual_quantity']);
					Product_Warehouse::availableQuantityIncrease(0, $i['product_basic_id'], $warehouse_id, $i['actual_quantity']);
					Product_Warehouse::purchaseBudgetQuantityDecrease(0, $i['product_basic_id'], $warehouse_id, $i['budget_quantity']);
					Product_Warehouse::purchaseActualQuantityDecrease(0, $i['product_basic_id'], $warehouse_id, $i['actual_quantity']);
					Product_Warehouse::purchaseQuantityDecrease(0, $i['product_basic_id'], $warehouse_id, $i['actual_quantity']);
					Product_Basic::updatePurchasePrice($i['product_basic_id'], $i['actual_price']);
				}
				$empty_actual_quantity_item = Purchase_Order_Item::find('purchase_order_id=? and actual_quantity=0 and audit_flag=' . Q::ini('custom_flag/purchase_order_item_audit_flag/unaudited/value'), $id)->asArray()->getAll();
				if ($empty_actual_quantity_item)
				{
					foreach ($empty_actual_quantity_item as $eaqi)
					{
						QDB::getConn()->execute('update purchase_order_item set audit_flag=' . Q::ini('custom_flag/purchase_order_item_audit_flag/audited/value') . ', audit_time=\'' . CURRENT_DATETIME . '\', audit_user_id=' . CURRENT_USER_ID . ' where id=' . $eaqi['id']);
						Product_Warehouse::purchaseBudgetQuantityDecrease(0, $eaqi['product_basic_id'], $warehouse_id, $eaqi['budget_quantity']);
					}
				}
			}
			else
			{
				$message[] = $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => FAILURE, 'message' => implode("\n", $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 财务审核采购入库单（可多个）
	 * @param $purchase_order_ids 采购入库单id数组
	 */
	static function auditFinance($purchase_order_ids)
	{
		$message = array();
		foreach ($purchase_order_ids as $key => $id)
		{
			$judge_result = Purchase_Order::judgeAuditFinance($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				QDB::getConn()->execute('update purchase_order set finance_audit=' . Q::ini('custom_flag/purchase_order_finance_audit/audited/value') . ',finance_audit_user_id=' . CURRENT_USER_ID . ', finance_audit_time=\'' . CURRENT_DATETIME . '\' where id=' . $id);
			}
			else
			{
				$message[] = $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => FAILURE, 'message' => implode("\n", $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 仓库审核采购退货单
	 * @param $drawback_ids 采购退货单id数组
	 */
	static function auditDrawbackStorage($drawback_ids)
	{
		$default_currency = Currency::getDefaultCurrency();
		$message = array();
		foreach ($drawback_ids as $key => $id)
		{
			$judge_result = Purchase_Order::judgeDrawbackAuditStorage($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				$drawback = Purchase_Order::find('id=?', $id)->getOne();
				$warehouse_id = $drawback['warehouse_id'];
				$drawback->status = Q::ini('custom_flag/purchase_order_status/storaged/value');
				$drawback->storage_audit_user_id = CURRENT_USER_ID;
				$drawback->storage_audit_time = CURRENT_DATETIME;
				$drawback->save();
				$item = Purchase_Order_Item::find('purchase_order_id=?', $id)->asArray()->getAll();
				foreach ($item as $i)
				{
					$cost_amount_result = Inventory_Log::getCostAmountByFIFO($i['product_basic_id'], $warehouse_id, $i['actual_quantity']);
					$log = new Inventory_Log();
					$log->product_basic_id = $i['product_basic_id'];
					$log->warehouse_id = $warehouse_id;
					$log->type = Q::ini('custom_flag/inventory_log_type/purchase_drawback/value');
					$log->relate_table_id = $i['id'];
					$log->init_quantity = 0;
					$log->in_quantity = 0;
					$log->out_quantity = $i['actual_quantity'];
					$log->cost_price = $cost_amount_result['cost_amount'] / $i['actual_quantity'];
					$log->sales_price = $i['actual_price'];
					$log->cost_amount = $cost_amount_result['cost_amount'];
					$log->sales_amount = $i['actual_price'] * $i['actual_quantity'];
					$log->currency_rate = $default_currency['rate'];
					$log->currency_id = $default_currency['id'];
					$log->remaining_quantity = 0;
					$log->user_id = CURRENT_USER_ID;
					$log->time = CURRENT_DATETIME;
					$log->save();
					Product_Warehouse::actualQuantityDecrease(0, $i['product_basic_id'], $warehouse_id, $i['actual_quantity']);
				}
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ' ' . $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => FAILURE, 'message' => implode(',', $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 财务审核采购退货单
	 * @param $drawback_ids 采购退货单id数组
	 */
	static function auditDrawbackFinance($drawback_ids)
	{
		$message = array();
		foreach ($drawback_ids as $key => $id)
		{
			$judge_result = Purchase_Order::judgeDrawbackAuditFinance($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				QDB::getConn()->execute('update purchase_order set finance_audit=' . Q::ini('custom_flag/purchase_order_finance_audit/audited/value') . ',finance_audit_user_id=' . CURRENT_USER_ID . ', finance_audit_time=\'' . CURRENT_DATETIME . '\' where id=' . $id);
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ' ' . $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => FAILURE, 'message' => implode(',', $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 判断采购单是否能够修改预计信息
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeEditBudget($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['type'] == Q::ini('custom_flag/purchase_order_type/order/value')
				&& $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'cannot edit budget');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'purchase order is not exists');
		}
	}
	
	/**
	 * 判断采购单是否能够修改实际采购信息
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeEditActual($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['type'] == Q::ini('custom_flag/purchase_order_type/order/value'))
			{
				if (in_array($purchase_order['warehouse_id'], Warehouse::getWarehouseIdsByType('baozhou')))
				{
					$purchase_order_status = array(
						Q::ini('custom_flag/purchase_order_status/purchasing/value'),
						Q::ini('custom_flag/purchase_order_status/purchased/value'),
						Q::ini('custom_flag/purchase_order_status/arrived/value'),
						Q::ini('custom_flag/purchase_order_status/partial_storaged/value')
					);
				}
				else
				{
					$purchase_order_status = array(
						Q::ini('custom_flag/purchase_order_status/purchasing/value'),
						Q::ini('custom_flag/purchase_order_status/purchased/value'),
						Q::ini('custom_flag/purchase_order_status/arrived/value')
					);
				}
				if (in_array($purchase_order['status'], $purchase_order_status))
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => '该采购单状态不能修改实际');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '该采购单不是入库单类型，请检查该单是否是入库单？');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '该订单不存在！');
		}
	}
	
	/**
	 * 判断采购单是否能够删除
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeDel($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['type'] == Q::ini('custom_flag/purchase_order_type/order/value')
				&& $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'cannot delete');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'purchase order is not exists');
		}
	}
	
	/**
	 * 判断采购单是否可以购前审核
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeAuditPurchase($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['type'] == Q::ini('custom_flag/purchase_order_type/order/value')
				&& $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '采购单' . $purchase_order['number'] . '状态不允许');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购单' . $purchase_order['number'] . '不存在');
		}
	}
	
	/**
	 * 判断是采购单否可以审核已采购状态为已到仓状态
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeAuditWarehoused($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['type'] == Q::ini('custom_flag/purchase_order_type/order/value') && $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/purchased/value'))
			{
				if ($purchase_order['purchase_hold_flag'] == Q::ini('custom_flag/purchase_hold_flag/unhold/value'))
				{
					$item = Purchase_Order_Item::find('purchase_order_id=?', $purchase_order['id'])->asArray()->getAll();
					$audit_flag = false;
					foreach ($item as $i)
					{
						if ($i['audit_flag'] == Q::ini('custom_flag/purchase_order_item_audit_flag/audited/value'))
						{
							$audit_flag = true;
						}
					}
					if ($audit_flag)
					{
						return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：采购单存在已审核入库产品，请联系系统技术人员！');
					}
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：该单已滞留！');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：该单状态错误！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '该单不存在！');
		}
	}
	
	/**
	 * 判断采购单是否可以仓库审核入库
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeAuditStorageSingle($purchase_order_item_id)
	{
		$default_warehouse_id = Warehouse::getDefaultWarehouseId();
		$item_columns = array(
				'purchase_order_item.*',
				'purchase_order.type as purchase_order_type, purchase_order.status as purchase_order_status, purchase_order.warehouse_id',
				'product_basic.weight, product_basic.declared_value, product_basic.declared_name_cn, product_basic.declared_name_en',
				'product_warehouse.shelf_position, product_warehouse.product_feature, product_warehouse.product_material_id'
		);
		$purchase_order_item = Purchase_Order_Item::find('purchase_order_item.id=?', $purchase_order_item_id)
			->joinLeft('purchase_order', '', 'purchase_order.id=purchase_order_item.purchase_order_id')
			->joinLeft('product_basic', '', 'product_basic.id=purchase_order_item.product_basic_id')
			->joinLeft('product_warehouse', '', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=purchase_order.warehouse_id')
			->setColumns($item_columns)->asArray()->getOne();
		if ($purchase_order_item['id'])
		{
			if ($purchase_order_item['purchase_order_type'] == Q::ini('custom_flag/purchase_order_type/order/value')
					&& ($purchase_order_item['purchase_order_status'] == Q::ini('custom_flag/purchase_order_status/arrived/value')
					|| $purchase_order_item['purchase_order_status'] == Q::ini('custom_flag/purchase_order_status/partial_storaged/value'))
					&& in_array($purchase_order_item['warehouse_id'], Warehouse::getWarehouseIdsByType('gz')))
			{
// 				if ( ! (trim($purchase_order_item['shelf_position']) || trim($purchase_order_item['product_feature'])) || ! $purchase_order_item['product_material_id'] || ! floatval($purchase_order_item['weight']) || ! floatval($purchase_order_item['declared_value']) || ! trim($purchase_order_item['declared_name_cn']) || ! trim($purchase_order_item['declared_name_en']))
// 				{
					
// 					return array('ack' => FAILURE, 'message' => '信息不全');
// 				}
// 				else
// 				{
					return array('ack' => SUCCESS, 'message' => '');
// 				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '采购单状态错误');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购单不存在');
		}
	}
	
	/**
	 * 判断采购单是否可以发送海外仓
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeAuditSend($purchase_order_id)
	{
		$check_in_db = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($check_in_db)
		{
			if ($check_in_db['status'] == Q::ini('custom_flag/purchase_order_status/arrived/value'))
			{
				if (in_array($check_in_db['warehouse_id'], Warehouse::getWarehouseIdsByType('baozhou')))
				{
					return array('ack' => FAILURE, 'message' => $check_in_db['number'] . '：默认仓订单，不需要发送！');
				}
				return array('ack' => SUCCESS, 'meesage' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $check_in_db['number'] . '：采购单状态有误！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购单id=' . $purchase_order_id . '不存在系统！');
		}
	}
	
	/**
	 * 判断采购单是否可以仓库审核入库
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeAuditStorage($purchase_order_id)
	{
		$item_columns = array(
			'purchase_order_item.*',
			'product_basic.weight, product_basic.declared_value, product_basic.declared_name_cn, product_basic.declared_name_en',
			'product_warehouse.shelf_position, product_warehouse.product_material_id'
		);
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['type'] == Q::ini('custom_flag/purchase_order_type/order/value')
				&& ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/arrived/value')
				|| $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/partial_storaged/value')
				|| $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/send/value')))
			{
				$default_warehouse_id = Warehouse::getDefaultWarehouseId();
				if ($purchase_order['warehouse_id'] == $default_warehouse_id)
				{
					$item = Purchase_Order_Item::find('purchase_order_item.purchase_order_id=? and purchase_order_item.actual_quantity>0', $purchase_order['id'])
						->joinLeft('product_basic', '', 'product_basic.id=purchase_order_item.product_basic_id')
						->joinLeft('product_warehouse', '', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
						->setColumns($item_columns)->asArray()->getAll();
					$info_complete = true;
// 					foreach ($item as $i)
// 					{
// 						if ( ! trim($i['shelf_position']) || ! $i['product_material_id'] || ! floatval($i['weight']) || ! floatval($i['declared_value']) || ! trim($i['declared_name_cn']) || ! trim($i['declared_name_en']))
// 						{
// 							$info_complete = false;
// 						}
// 					}
					if ($info_complete)
					{
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：产品信息不全，检查价位、包材、重量、申报信息！');
					}
				}
				else
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：状态有误，不允许入库！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购单不存在！采购单ID=' . $purchase_order_id);
		}
	}
	
	/**
	 * 判断采购单能否财务审核
	 * @param $purchase_order_id 采购入库单id
	 */
	static function judgeAuditFinance($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['type'] == Q::ini('custom_flag/purchase_order_type/order/value')
				&& ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/storaged/value') || $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/send/value'))
				&& $purchase_order['finance_audit'] == Q::ini('custom_flag/purchase_order_finance_audit/unaudit/value'))
			{
				$item_actual_amount = QDB::getConn()->execute('select round(sum(actual_price*actual_quantity),4) from purchase_order_item where purchase_order_id=' . $purchase_order['id'])->fetchOne();
				if ($purchase_order['actual_amount'] == $item_actual_amount)
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：采购单总金额跟实际总金额不等！');
				}
				
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $purchase_order['number'] . '：采购单类型或状态有误，不能财务审核！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购单不存在！');
		}
	}
	
	/**
	 * 判断采购退货单满足创建条件
	 * @param $drawback 退货单信息
	 */
	static function judgeCreateDrawback($drawback)
	{
		if ($drawback['payment_type'] == Q::ini('custom_flag/purchase_order_payment_type/period/value'))
		{
			$res = array_column($drawback['item'], 'actual_provider_id');
			if (count(array_unique($res)) != 1)
			{
				return array('ack' => FAILURE, 'message' => '周期结款采购单供应商不一致！');
			}
		}
		$tmp = array();
		foreach ($drawback['item'] as $i)
		{
			$product_warehouse = Product_Warehouse::find('warehouse_id=? and product_basic_id=?', $drawback['warehouse_id'], $i['product_basic_id'])->asArray()->getOne();
			if ($product_warehouse)
			{
				if ( ! array_key_exists($i['product_basic_id'], $tmp))
				{
					$tmp[$i['product_basic_id']]['need_quantity'] = 0;
					$tmp[$i['product_basic_id']]['available_quantity'] = $product_warehouse['available_quantity'];
				}
				$tmp[$i['product_basic_id']]['need_quantity'] += $i['actual_quantity'];
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '产品ID=' . $i['product_basic_id'] . '不存在！');
			}
		}
		foreach ($tmp as $t)
		{
			if ($t['need_quantity'] > $t['available_quantity'])
			{
				return array('ack' => FAILURE, 'message' => '产品可用数量不足，请检查系统可用库存！');
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	/**
	 * 判断采购退货单是否满足编辑条件
	 * @param $drawback 退货单信息
	 */
	static function judgeEditDrawback($drawback)
	{
		$check_in_db = Purchase_Order::find('id=?', $drawback['id'])->asArray()->getOne();
		if ($check_in_db)
		{
			if ($check_in_db['type'] == Q::ini('custom_flag/purchase_order_type/drawback/value')
				&& $check_in_db['status'] == Q::ini('custom_flag/purchase_order_status/new/value'))
			{
				if ($drawback['payment_type'] == Q::ini('custom_flag/purchase_order_payment_type/period/value'))
				{
					$res = array_column($drawback['item'], 'actual_provider_id');
					if (count(array_unique($res)) != 1)
					{
						return array('ack' => FAILURE, 'message' => '周期结款采购单供应商不一致！');
					}
				}
				$tmp = array();
				foreach ($drawback['item'] as $i)
				{
					$product_warehouse = Product_Warehouse::find('warehouse_id=? and product_basic_id=?', $check_in_db['warehouse_id'], $i['product_basic_id'])->asArray()->getOne();
					if ($product_warehouse)
					{
						if ( ! array_key_exists($i['product_basic_id'], $tmp))
						{
							$already_use = Purchase_Order_Item::find('purchase_order_id=? and product_basic_id=?', $check_in_db['id'], $i['product_basic_id'])->getSum('actual_quantity');
							$tmp[$i['product_basic_id']]['need_quantity'] = 0;
							$tmp[$i['product_basic_id']]['available_quantity'] = $product_warehouse['available_quantity'] + $already_use;
						}
						$tmp[$i['product_basic_id']]['need_quantity'] += $i['actual_quantity'];
					}
					else
					{
						return array('ack' => FAILURE, 'message' => '产品ID=' . $i['product_basic_id'] . '不存在！');
					}
				}
				foreach ($tmp as $t)
				{
					if ($t['need_quantity'] > $t['available_quantity'])
					{
						return array('ack' => FAILURE, 'message' => '产品可用数量不足，请检查系统可用库存！');
					}
				}
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '采购退货单状态有误！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购退货单不存在！');
		}
	}
	
	/**
	 * 判断采购退货单是否能够删除
	 * @param $drawback_id 采购退货单id
	 */
	static function judgeDelDrawback($drawback_id)
	{
		$drawback = Purchase_Order::find('id=?', $drawback_id)->asArray()->getOne();
		if ($drawback)
		{
			if ($drawback['type'] == Q::ini('custom_flag/purchase_order_type/drawback/value')
				&& $drawback['status'] == Q::ini('custom_flag/purchase_order_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'status not allow');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'purchase drawback not exists');
		}
	}
	
	/**
	 * 判断采购退货单是否满足仓库审核条件
	 * @param $drawback_id 采购退货单id
	 */
	static function judgeDrawbackAuditStorage($drawback_id)
	{
		$drawback = Purchase_Order::find('id=?', $drawback_id)->asArray()->getOne();
		if ($drawback)
		{
			if ($drawback['type'] == Q::ini('custom_flag/purchase_order_type/drawback/value')
				&& $drawback['status'] == Q::ini('custom_flag/purchase_order_status/new/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => 'status not allow');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'purchase drawback not exists');
		}
	}
	
	/**
	 * 判断采购退货单是否可以财务审核
	 * @param $drawback_id
	 */
	static function judgeDrawbackAuditFinance($drawback_id)
	{
		$drawback = Purchase_Order::find('id=?', $drawback_id)->asArray()->getOne();
		if ($drawback)
		{
			if ($drawback['type'] == Q::ini('custom_flag/purchase_order_type/drawback/value')
				&& $drawback['status'] == Q::ini('custom_flag/purchase_order_status/storaged/value')
				&& $drawback['finance_audit'] == Q::ini('custom_flag/purchase_order_finance_audit/unaudit/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' =>  $drawback['number'] . '：采购退货单类型或状态有误，不能财务审核！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购退货单不存在！');
		}
	}
	
	/**
	 * 更新采购单信息
	 * @param $purchase_order_id 采购单id
	 */
	static function updateOrder($purchase_order_id)
	{
		$order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($order['id'])
		{
			$actual_amount = QDB::getConn()->execute('select sum(actual_quantity*actual_price) from purchase_order_item where purchase_order_id=' . $order['id'])->fetchOne();
			$actual_amount = $actual_amount ? $actual_amount : 0;
			QDB::getConn()->execute('update purchase_order set actual_amount =' . $actual_amount . ' where purchase_order.id=' . $order['id']);
			return array('ack' => SUCCESS, 'message' => '');
		}
		return array('ack' => FAILURE, 'message' => 'purchase order is not exists');
	}
	
	/**
	 * 取消滞留采购单
	 * @param $purchase_order_ids 采购单id
	 */
	static function changePurchaseHoldFlag($purchase_order_ids)
	{
		$message = array();
		foreach ($purchase_order_ids as $id)
		{
			$judge_result = Purchase_Order::judgeChangePurchaseHoldFlag($id);
			if ($judge_result['ack'] == SUCCESS)
			{
				QDB::getConn()->execute('update purchase_order set purchase_hold_flag=' . Q::ini('custom_flag/purchase_hold_flag/unhold/value') . ' where id=' . $id);
			}
			else
			{
				$message[] = $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => PARTIAL_FAILURE, 'message' => implode("\n", $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 已滞留变为未滞留判断
	 * @param $purchase_order_id 采购单id
	 */
	static function judgeChangePurchaseHoldFlag($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['purchase_hold_flag'] == Q::ini('custom_flag/purchase_hold_flag/holded/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $purchase_order['number'] . ': 该订单滞留状态是：' . Helper_BSS_Normal::getIniOne('purchase_hold_flag', 'value', $purchase_order['purchase_hold_flag'], 'name'));
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购单ID：' . $purchase_order_id . '不存在！');
		}
	}
	
	/**
	 * 设置限制采购人员显示和权限的控制
	 * @param $type 类型
	 */
	static function getUser($type=false)
	{
		$ack = false;
		$user = $users = array();
		if ($type)
		{
			$action = Permissions_Actions::find('namespace=? and controller=? and action=?', $_GET['namespace'], $_GET['controller'], $_GET['action'])->asArray()->getOne();
			if ($action)
			{
				$user = User::find('user.id=roles_users_mapping.user_id')
					->joinLeft('roles_actions_mapping', '', 'roles_actions_mapping.roles_id!=1 and roles_actions_mapping.permissions_actions_id=' . $action['id'])
					->joinLeft('roles_users_mapping', '', 'roles_users_mapping.roles_id=roles_actions_mapping.roles_id')
					->asArray()->getAll();
			}
		}
		else
		{
			$user = User::find('status=? and id in (?)', Q::ini('custom_flag/user_status/on_duty/value'), array(Q::ini('custom_flag/info/purchase_manager/value'),Q::ini('custom_flag/info/product_manager/value')), array(Q::ini('custom_flag/info/purchase_manager/value')))->asArray()->getAll();
			foreach ($user as $u)
			{
				$user = array_merge($user, User::getOffspringById($u['id']));
			}
			
			//权限限制是否只显示自己的订单
			$current = User::find('id=?', CURRENT_USER_ID)->asArray()->getOne();
			$has_child = User::find('parent_id=?', CURRENT_USER_ID)->asArray()->getAll();
			if ($current['parent_id'] != 1 && !$has_child)
			{
				$ack = true;
			}
		}
		return array('ack' => $ack, 'data' => $user);
	}
	
	/**
	 * 按条件搜索采购单
	 * @param $condition 条件
	 * @param $cp 当前页
	 * @param $ps 每页大小
	 */
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'purchase_order.*',
			'user.name as purchase_user_name',
			'a.name as complete_user_name',
			'b.name as arrive_user_name',
			'c.name as send_user_name',
			'd.name as storage_user_name',
			'e.name as finance_user_name',
			'warehouse.name as warehouse_name'
		);
		$where = Purchase_Order::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Purchase_Order::find($where)
				->joinLeft('user', '', 'user.id=purchase_order.purchase_user_id')
				->joinLeft('user as a', '', 'a.id=purchase_order.complete_user_id')
				->joinLeft('user as b', '', 'b.id=purchase_order.arrive_user_id')
				->joinLeft('user as c', '', 'c.id=purchase_order.send_user_id')
				->joinLeft('user as d', '', 'd.id=purchase_order.storage_audit_user_id')
				->joinLeft('user as e', '', 'e.id=purchase_order.finance_audit_user_id')
				->joinLeft('warehouse', '', 'warehouse.id=purchase_order.warehouse_id')
				->order('purchase_order.make_time desc')->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Purchase_Order::find($where)
				->joinLeft('user', '', 'user.id=purchase_order.purchase_user_id')
				->joinLeft('user as a', '', 'a.id=purchase_order.complete_user_id')
				->joinLeft('user as b', '', 'b.id=purchase_order.arrive_user_id')
				->joinLeft('user as c', '', 'c.id=purchase_order.send_user_id')
				->joinLeft('user as d', '', 'd.id=purchase_order.storage_audit_user_id')
				->joinLeft('user as e', '', 'e.id=purchase_order.finance_audit_user_id')
				->joinLeft('warehouse', '', 'warehouse.id=purchase_order.warehouse_id')
				->order('purchase_order.make_time desc')->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$purchase_order = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $purchase_order,
			'pagination' => $pagination
		);
	}
	
	/**
	 * 组装搜索条件
	 * @param $condition 条件数组
	 */
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (isset($condition['limit']) && $condition['limit'] || CURRENT_USER_NAME == 'langyi')
		{
			$where .= ' and purchase_order.purchase_user_id=' . CURRENT_USER_ID;
		}
		if (isset($condition['id']))
		{
			$where .= ' and purchase_order.id in (\'' . implode('\',\'', $condition['id']) . '\')';
		}
		if ( ! empty($condition['warehouse_id']))
		{
			if (is_array($condition['warehouse_id']))
			{
				$where .= ' and purchase_order.warehouse_id in (\'' . implode('\',\'', $condition['warehouse_id']) . '\')';
			}
			else
			{
				$where .= ' and purchase_order.warehouse_id=' . $condition['warehouse_id'];
			}
		}
		if ( ! empty($condition['type']))
		{
			$where .= ' and purchase_order.type=' . $condition['type'];
		}
		if ( ! empty($condition['purchase_order_payment_type']))
		{
			$where .= ' and purchase_order.payment_type=' . $condition['purchase_order_payment_type'];
		}
		if ( ! empty($condition['begin_purchase_time']))
		{
			$where .= ' and purchase_order.purchase_time>=\'' . $condition['begin_purchase_time'] . '\'';
		}
		if ( ! empty($condition['end_purchase_time']))
		{
			$where .= ' and purchase_order.purchase_time<=\'' . $condition['end_purchase_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['begin_storage_audit_time']))
		{
			$where .= ' and purchase_order.storage_audit_time>=\'' . $condition['begin_storage_audit_time'] . '\'';
		}
		if ( ! empty($condition['end_storage_audit_time']))
		{
			$where .= ' and purchase_order.storage_audit_time<=\'' . $condition['end_storage_audit_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['begin_finance_audit_time']))
		{
			$where .= ' and purchase_order.finance_audit_time>=\'' . $condition['begin_finance_audit_time'] . '\'';
		}
		if ( ! empty($condition['end_finance_audit_time']))
		{
			$where .= ' and purchase_order.finance_audit_time<=\'' . $condition['end_finance_audit_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['purchase_order_number']))
		{
			$where .= ' and purchase_order.number=\'' . $condition['purchase_order_number'] .'\'';
		}
		if ( ! empty($condition['purchase_user_id']))
		{
			$where .= ' and purchase_order.purchase_user_id=\'' . $condition['purchase_user_id'] . '\'';
		}
		if ( ! empty($condition['ajax_provider']))
		{
			$actual_provider_id = explode(' ', $condition['ajax_provider']);
			$item = Purchase_Order_Item::find('actual_provider_id=?', $actual_provider_id[0])->asArray()->getAll();
			if ($item)
			{
				$purchase_order_ids = array();
				foreach ($item as $i)
				{
					$purchase_order_ids[] = $i['purchase_order_id'];
				}
				$where .= ' and purchase_order.id in (' . implode(',', $purchase_order_ids) . ')';
			}
			else
			{
				$where .= ' and purchase_order.id=0';
			}
		}
		if ( ! empty($condition['product_basic_number']))
		{
			$item = Purchase_Order_Item::find('product_basic.number=?', $condition['product_basic_number'])
				->joinLeft('product_basic', '', 'product_basic.id=purchase_order_item.product_basic_id')
				->asArray()->getAll();
			if ($item)
			{
				$purchase_order_ids = array();
				foreach ($item as $i)
				{
					$purchase_order_ids[] = $i['purchase_order_id'];
				}
				$where .= ' and purchase_order.id in (' . implode(',', $purchase_order_ids) . ')';
			}
			else
			{
				$where .= ' and purchase_order.id=0';
			}
		}
		if (isset($condition['is_fba']) && $condition['is_fba'])
		{
			$purchase_order_status = array(
				Q::ini('custom_flag/purchase_order_status/purchased/value') => Q::ini('custom_flag/purchase_order_status/purchased/value'), 
				Q::ini('custom_flag/purchase_order_status/arrived/value') => Q::ini('custom_flag/purchase_order_status/arrived/value'),
				Q::ini('custom_flag/purchase_order_status/send/value') => Q::ini('custom_flag/purchase_order_status/send/value'),
				Q::ini('custom_flag/purchase_order_status/storaged/value') => Q::ini('custom_flag/purchase_order_status/storaged/value')
			);
			$where .= ' and purchase_order.status in (' . implode(',', $purchase_order_status) . ')';
		}
		if (isset($condition['purchase_order_status']))
		{
			$purchase_order_status_filter = '0';
			foreach (Q::ini('custom_flag/purchase_order_status') as $pos)
			{
				if (isset($condition['purchase_order_status'][$pos['value']]) && $condition['purchase_order_status'][$pos['value']] == $pos['value'])
				{
					$purchase_order_status_filter .= ' or purchase_order.status=' . $pos['value'];
				}
			}
			$where .= ' and (' . $purchase_order_status_filter . ')';
		}
		if (isset($condition['audit_status']))
		{
			$where .= ' and (purchase_order.status=\'' . Q::ini('custom_flag/purchase_order_status/new/value') . '\' or purchase_order.status=\'' . Q::ini('custom_flag/purchase_order_status/purchasing/value') . '\' or purchase_order.status=\'' . Q::ini('custom_flag/purchase_order_status/purchased/value') . '\')'; 
		}
		if (isset($condition['finance_audit']))
		{
			$finance_audit_filter = '0';
			foreach (Q::ini('custom_flag/purchase_order_finance_audit') as $fa)
			{
				if (isset($condition['finance_audit'][$fa['value']]) && $condition['finance_audit'][$fa['value']] == $fa['value'])
				{
					$finance_audit_filter .= ' or purchase_order.finance_audit=' . $fa['value'];
				}
			}
			$where .= ' and (' . $finance_audit_filter . ')';
		}
		if (isset($condition['status']))
		{
			$status_fitler = '0';
			if (isset($condition['status'][1]))
			{
				$status_fitler .= ' or purchase_order.status=' . Q::ini('custom_flag/purchase_order_status/new/value');
			}
			if (isset($condition['status'][4]))
			{
				$status_fitler .= ' or purchase_order.status=' . Q::ini('custom_flag/purchase_order_status/storaged/value');
			}
			$where .= " and ($status_fitler)";
		}
		if (isset($condition['current_user_id']))
		{
			$where .= ' and purchase_user_id=' . $condition['current_user_id'];
		}
		if (! empty($condition['begin_cross_days_time']) || ! empty($condition['end_cross_days_time']))
		{
			$cross_days_where = 'DATEDIFF(purchase_order.storage_audit_time, purchase_order_item.audit_time) >= 1';
			if(! empty($condition['begin_cross_days_time']))
			{
				$cross_days_where .= ' and purchase_order.storage_audit_time>\'' . $condition['begin_cross_days_time'] . '\'';
			}
			if(! empty($condition['end_cross_days_time']))
			{
				$cross_days_where .= ' and purchase_order.storage_audit_time<\'' . $condition['end_cross_days_time'] . ' 23:59:59\'';
			}
			$purchase_order_id = Purchase_Order_Item::find($cross_days_where)
				->joinleft('purchase_order', '', 'purchase_order_item.purchase_order_id=purchase_order.id')
				->setcolumns('purchase_order.id')->group('purchase_order_item.purchase_order_id')->asArray()->getAll();
			$id = '';
			foreach ($purchase_order_id as $poi)
			{
				$id .= '\'' . $poi['id'] . '\',';
			}
			$where .= ' and purchase_order.id in (' . (empty($id) ? '\'\'' : rtrim($id, ',')) . ')';
		}
		if (! empty($condition['is_diff_flag']))
		{
			$where .= ' and purchase_order.budget_amount!=purchase_order.actual_amount';
		}
		if (! empty($condition['timeout_purchase_order']))
		{
			$where .= ' and TIMESTAMPDIFF(DAY, purchase_order.arrive_time, now())>=5 and purchase_order.status=' . Q::ini('custom_flag/purchase_order_status/arrived/value');
		}
		if (isset($condition['purchase_hold_flag']))
		{
			$purchase_hold_flag_filter = '0';
			foreach (Q::ini('custom_flag/purchase_hold_flag') as $hf)
			{
				if (isset($condition['purchase_hold_flag'][$hf['value']]) && $condition['purchase_hold_flag'][$hf['value']] == $hf['value'])
				{
					$purchase_hold_flag_filter .= ' or purchase_order.purchase_hold_flag=' . $hf['value'];
				}
			}
			$where .= ' and (' . $purchase_hold_flag_filter . ')';
		}
		return $where;
	}
}